﻿#include "UserDetailShowDlg.h"


UserDetailShowDlg::UserDetailShowDlg(QWidget* parent)
	:QWidget(parent)
{
	this->setWindowTitle("用户详细信息显示");
	this->resize(600, 200);		
	this->setWindowFlag(Qt::FramelessWindowHint);										//去掉边框和状态栏；
	QObject::installEventFilter(new eventFilterObject(this));							//自由拖动窗口
	this->setStyleSheet(R"(background-color:rgb(40,40,40);color:white;)");
	this->setAttribute(Qt::WA_StyledBackground);										//根据样式来绘制背景
	//this->setWindowFlag(Qt::WindowStaysOnTopHint);										//设置窗口置顶

	init();
}

void UserDetailShowDlg::init()
{
	//整体布局：
	auto Totality_layout = new QVBoxLayout(this);

	//窗口顶层的标题和关闭按钮部分的布局：
	{
		auto hlayout = new QHBoxLayout;

		//标题：
		auto title = new QLabel("User Details Window >");
		title->setStyleSheet("font:bold 13px");						//设置标题为加粗字体，再设置字体大小为13px；
		hlayout->addWidget(title);

		hlayout->addStretch();

		//关闭按钮：
		m_closeBtn = new QPushButton;
		m_closeBtn->setIcon(QIcon(":/ClientResource/close.png"));				//设置关闭按钮的图标
		hlayout->addWidget(m_closeBtn);

		//把顶层部分添加到总体布局上：
		Totality_layout->addLayout(hlayout);
	}

	//返回按钮部分布局：
	{
		auto hlayout = new QHBoxLayout;

		m_backBtn = new QPushButton;
		m_backBtn->setStyleSheet("border:none; font:bold 18px; color:rgb(195,232,141)");				//设置样式表
		m_backBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
		hlayout->addWidget(m_backBtn);

		hlayout->addWidget(new QLabel("    ——————————————————————"));

		auto pngLabel = new QLabel;
		pngLabel->setPixmap(QPixmap(":/ClientResource/show.png"));
		hlayout->addWidget(pngLabel);

		//添加到总体布局中：
		Totality_layout->addLayout(hlayout);
	}

	Totality_layout->addSpacerItem(new QSpacerItem( 1, 15));			//向布局中添加一个空白项（spacer item）。这个空白项是一个占位符，用来控制布局中部件的间距和位置
	/*
		这行代码创建了一个新的QSpacerItem对象，宽度为1个像素，高度为30个像素，并将其添加到vlayout中。这可以用来在垂直布局中创建一个固定高度的空白区域，用于调整布局中部件的位置和间距
	*/

	//用户信息标签部分布局：
	auto UserInformationTag_layout = new QHBoxLayout;
	UserInformationTag_layout->addWidget(new QLabel("用户基本信息"));
	m_editBtn = new QPushButton("编辑基本信息");
	//下面是设置按钮中字体下滑线的操作：
					QFont font = m_editBtn->font();
					font.setUnderline(true);
					m_editBtn->setFont(font);
	m_editBtn->setStyleSheet("border:none;color:rgb(97,162,243);");				//设置样式表
	UserInformationTag_layout->addWidget(m_editBtn);
	m_resetpwBtn = new QPushButton("重置密码");
					font = m_resetpwBtn->font();
					font.setUnderline(true);
					m_resetpwBtn->setFont(font);
	m_resetpwBtn->setStyleSheet("border:none;color:rgb(97,162,243);");			//设置样式表
	UserInformationTag_layout->addWidget(m_resetpwBtn);
	m_deluserBtn = new QPushButton("删除用户");
					font = m_deluserBtn->font();
					font.setUnderline(true);
					m_deluserBtn->setFont(font);
	m_deluserBtn->setStyleSheet("border:none;color:rgb(97,162,243);");			//设置样式表
	UserInformationTag_layout->addWidget(m_deluserBtn);
	UserInformationTag_layout->addStretch();				//弹簧
	//将用户信息标签部分布局添加到整体布局中：
	Totality_layout->addLayout(UserInformationTag_layout);


	//用户基本信息部分布局：
	{
		//左布局：
		auto left_layout = new QFormLayout;
		//右布局：
		auto right_layout = new QFormLayout;

		m_avatar_lab = new QLabel;
		m_user_id_lab = new QLabel;
		m_username_lab = new QLabel;
		m_mobile_lab = new QLabel;
		m_email_lab = new QLabel;
		m_isenable_btn = new SSwitchButton;
		m_isenable_btn->setFixedWidth(40);				//设置按钮的大小

		//设置默认头像：
		m_avatar_lab->setPixmap(QPixmap(":/ClientResource/default_avatar.jpg"));
		m_avatar_lab->setFixedSize(58, 58);												//设置头像的大小			注意，这个一定要先写，不然图片显示不出来
		//m_avatar_lab->setMask(QRegion(m_avatar_lab->rect(), QRegion::RegionType::Ellipse));		//设置该标签的所有矩形区域的形状为圆形
		m_avatar_lab->setScaledContents(true);													//设置 QLabel 控件中显示的图像是否按比例缩放
		m_avatar_modifyBtn = new QPushButton("更换头像");
		m_avatar_modifyBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
		m_avatar_modifyBtn->setStyleSheet("border:none; background-color:rgb(33,33,33);color:rgb(117,249,77)");

		//头像部分布局:
		{
			auto hlayout = new QHBoxLayout;
			hlayout->addWidget(m_avatar_lab);
			hlayout->addWidget(m_avatar_modifyBtn);

			//添加到左布局中：
			left_layout->addRow(hlayout);
		}

		//左布局设置：
		left_layout->addRow("用户id >", m_user_id_lab);
		left_layout->addRow("用户名 >", m_username_lab);
		left_layout->addRow("账号状态 >", m_isenable_btn);

		//右布局设置：
		right_layout->addRow("", new QLabel);				//占位....
		right_layout->addRow("", new QLabel);				//占位....
		right_layout->addRow("", new QLabel);				//占位....
		right_layout->addRow("手机号码 >", m_mobile_lab);
		right_layout->addRow("电子邮箱 >", m_email_lab);

		//左右布局联合部分布局：
		auto hlayout = new QHBoxLayout;
		hlayout->addLayout(left_layout);
		hlayout->addSpacerItem(new QSpacerItem(60, 20));	//向布局中添加一个空白项（spacer item）。这个空白项是一个占位符，用来控制布局中部件的间距和位置
		hlayout->addLayout(right_layout);
		hlayout->addStretch();								//弹簧


		//将左右布局联合部分布局添加到总体布局：
		Totality_layout->addLayout(hlayout);
	}

	Totality_layout->addStretch();							//弹簧


	//信号槽连接：
	connectinit();

}

void UserDetailShowDlg::setUserData(const QJsonObject& object)
{
	//获取用户数据：
	m_Olduser = object;
	m_user = object;


	//部署用户数据信息：
	updateUi();

	//通过http获取用户头像：
	UserAvatar_Get_DownLoad();
}

void UserDetailShowDlg::updateUi()
{
	m_backBtn->setText(m_user.value("username").toString());
	m_user_id_lab->setText(m_user.value("user_id").toString());
	m_username_lab->setText(m_user.value("username").toString());
	m_mobile_lab->setText(m_user.value("mobile").toString());
	m_email_lab->setText(m_user.value("email").toString());
	m_isenable_btn->setToggle(m_user.value("isEnable").toInt());
}

void UserDetailShowDlg::connectinit()
{
	//关闭按钮，关闭窗口：
	connect(m_closeBtn, &QPushButton::clicked,this, [=]
		{
			this->close();
		});
	//返回按钮：
	connect(m_backBtn, &QPushButton::clicked, this, [=]
		{
			if (m_Olduser != m_user)
			{
				emit userDataChanged(m_user);
			}

			this->close();
		});

	//编辑基本信息按钮：
	connect(m_editBtn, &QPushButton::clicked, this, [=]()
		{
			if (!m_edituserDlg)
			{
				m_edituserDlg = new UserDetail_toEditUserDlg;

				connect(m_edituserDlg, &UserDetail_toEditUserDlg::userDataChanged, [=](const QJsonObject& object)
					{
						m_user = object;
						//this->show();
						MaskWidget::instance()->popup(this);
						updateUi();
					});
				connect(m_edituserDlg, &UserDetail_toEditUserDlg::windowclose, [=]
					{
						//this->show();
						MaskWidget::instance()->popup(this);
					});
			}

			m_edituserDlg->setUserData(m_user);
			this->hide();
			//m_edituserDlg->show();
			MaskWidget::instance()->popup(m_edituserDlg);
		});

	//重置密码按钮：
	connect(m_resetpwBtn, &QPushButton::clicked, this, [=]()
		{
			if (!m_modifypasswordDlg)
			{
				m_modifypasswordDlg = new UserDetail_toModifyPasswordDlg;

				connect(m_modifypasswordDlg, &UserDetail_toModifyPasswordDlg::UserDataChanged, [=](const QJsonObject& object)
					{
						m_user = object;
						this->show();
					});
				connect(m_modifypasswordDlg, &UserDetail_toModifyPasswordDlg::windowclose, [=]
					{
						//this->show();
						MaskWidget::instance()->popup(m_modifypasswordDlg);
					});
			}

			m_modifypasswordDlg->setUserData(m_user);
			this->hide();
			//m_modifypasswordDlg->show();
			MaskWidget::instance()->popup(m_modifypasswordDlg);
		});

	//删除用户按钮：
	connect(m_deluserBtn, &QPushButton::clicked, this, [=]()
		{
			//提示，毕竟删除是不可逆的：
			if (QMessageBox::No == QMessageBox::question(0, QObject::tr("tip~~~~"), "确定要删除该用户的数据么",QMessageBox::Ok | QMessageBox::No))
			{
				return;
			}


			QJsonObject object;
			object.insert("user_id_lists", QJsonArray{ { m_user.value("user_id").toString()} });


			SHttpClient(QUrl("http://" + sApp->globalConfig()->value("host/host").toString() + QString("/api/user/delete")))
				.debug(true)
					.header("Authorization", "Bearer" + sApp->userData("user/token").toString())
						.json(object)
							.fail([](const QString& msg, int code)
								{
									qDebug() << msg << code;
								})
								.success([=](const QByteArray& array)
									{
										QJsonParseError error;
										auto jdocument = QJsonDocument::fromJson(array, &error);

										if (jdocument["code"].toInt() == 0)
										{
											emit userDataDeleted(m_user);
											this->close();
										}

									})
									.post();
		});

	//修改头像按钮：
	connect(m_avatar_modifyBtn, &QPushButton::clicked, this, &UserDetailShowDlg::UserAvatar_Post_Update);

	//用户状态修改按钮：
	connect(m_isenable_btn, &SSwitchButton::stateChanged, [=](bool state)
		{
			SHttpClient(QUrl("http://" + sApp->globalConfig()->value("host/host").toString() + QString("/api/user/modify?user_id=") + m_user.value("user_id").toString()))
				.debug(true)
					.header("Authorization", "Bearer" + sApp->userData("user/token").toString())
						.json({{"isEnable",state ? 1 : 0}})
							.fail([](const QString& msg, int code)
								{
									qDebug() << msg << code;
								})
								.success([=](const QByteArray& array)
									{
										QJsonParseError error;
										auto jdocument = QJsonDocument::fromJson(array, &error);

										if (error.error != QJsonParseError::NoError)
										{
											return;
										}
										else
										{
											if (jdocument["code"].toInt() < 1000)
											{
												//数据库更新完后，模型中的数据还没有被修改：
												m_user.insert("isEnable", state);		//如果插入的键和已经存在的重复，那就会修改该值的值

												emit userDataChanged(m_user);
											}
										}
									})
									.post();
		});
}


void UserDetailShowDlg::UserAvatar_Get_DownLoad()
{
	SHttpClient(QUrl("http://" + sApp->globalConfig()->value("host/host").toString() + QString("/api/user/avatar")))
		.debug(true)
		.header("Authorization", "Bearer" + sApp->userData("user/token").toString())
		.param("user_id", m_user.value("user_id").toString())
		.fail([=](const QString& msg, int code)
			{
				qDebug() << msg << code;

				//如果获取头像失败，就设置默认头像：
				m_avatar_lab->setPixmap(QPixmap(":/ClientResource/default_avatar.jpg"));
			})
		.success([=](const QByteArray& array)
			{
				if (array.startsWith('{'))
				{
					QJsonParseError error;
					auto jdocument = QJsonDocument::fromJson(array, &error);

					m_avatar_lab->setPixmap(QPixmap(":/ClientResource/default_avatar.jpg"));
				}
				else
				{
					auto img = QImage::fromData(array);
					m_avatar_lab->setPixmap(QPixmap::fromImage(img));
				}
			})
				.get();
}

void UserDetailShowDlg::UserAvatar_Post_Update()
{
	auto path = sApp->globalConfig()->value("other/select_avatar_path",
		QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)).toString();

	auto filename = QFileDialog::getOpenFileName(this, "选择头像", path, "*.jpg;*.png;*.jpeg");
	if (filename.isEmpty())
	{
		return;
	}

	sApp->globalConfig()->setValue("other/select_avatar_path", QFileInfo(filename).canonicalPath());

	//图片文件打开失败：
	QFile file(filename);
	if (!file.open(QIODevice::ReadOnly))
	{
		QMessageBox::warning(this, "damm", "头像打开失败");
		return;
	}

	//图片文件的大小不能超多3Mb：
	if (file.size() > 3 * 1024 * 1024)
	{
		QMessageBox::warning(this, "damn", "图片文件过大，请选择小于3MB大小的文件");
		return;
	}


	//实现图片格式的多样化：
						//使用qt提供的原生HttpAccess来上传头像：
	QNetworkAccessManager* Netmanager = new QNetworkAccessManager(this);
	QNetworkRequest request(QUrl("http://" + sApp->globalConfig()->value("host/host").toString() + QString("/api/user/avatar?user_id=") + m_user.value("user_id").toString()));
	request.setRawHeader("Authorization", "Bearer" + sApp->userData("user/token").toString().toUtf8());
	request.setHeader(QNetworkRequest::KnownHeaders::ContentTypeHeader, "application/x-www-form-urlencoded");

	QHttpMultiPart* mpart = new QHttpMultiPart(this);
	QHttpPart part;
	part.setBody(file.readAll());
	part.setHeader(QNetworkRequest::ContentTypeHeader, QString("image/%1").arg(QFileInfo(filename).suffix()));
	part.setHeader(QNetworkRequest::ContentDispositionHeader,
		QString(R"(attachment;name="file";filename="%1")").arg(QFileInfo(filename).fileName()));
	mpart->append(part);

	auto reply = Netmanager->post(request, mpart);
	connect(reply, &QNetworkReply::finished, this, [=]
		{
			if (reply->error() != QNetworkReply::NoError)
			{
				qDebug() << "reply error" << reply->errorString();

				//如果失败了，就显示默认头像：
				m_avatar_lab->setPixmap(QPixmap(":/ClientResource/default_avatar.jpg"));
			}
			else
			{
				qDebug() <<"replay >" << QString(reply->readAll());

				//如果上传成功，就直接显示刚刚上传的头像：
				m_avatar_lab->setPixmap(QPixmap(filename));
			}
		});


}




